<#assign numbers=['Short','Integer','Long','Float','Double','BigDecimal']>
<#function mapping(collection, propertyName)>
    <#local values = []>
    <#list collection as item>
        <#local value = item[propertyName]>
        <#if value?exists>
            <#local values = values + [value]>
        </#if>
    </#list>
    <#return values>
</#function>

<template>
    <div>
        <div class="header">
            <div class="page-header">
                <el-page-header @back="goBack" content="${description}"></el-page-header>
            </div>

            <el-button type="success" icon="el-icon-plus" @click="openNewDialog()" size="small"
                       style="margin-top:10px;margin-left: 20px">新增
            </el-button>

            <el-button type="danger" icon="el-icon-delete" @click="delete${className}()" size="small"
                       :disabled="deleteable" style="margin-top:10px;margin-left: 20px">批量删除
            </el-button>

            <div class="search">
                <el-input v-model="pageRequest.key" style="width: 200px;margin-right: 10px"
                          placeholder="按${description}名称查找"
                          size="small"></el-input>
                <el-button type="primary" icon="el-icon-search" size="small" @click="get${className}List">搜索</el-button>
            </div>

        </div>
        <el-card class="box-card" shadow="always">
            <template>
                <el-table
                        ref="multipleTable"
                        @selection-change="handleSelectionChange"
                        :header-cell-style="{color:'#333',fontFamily:'MicrosoftYaHeiUI',fontSize:'14px',fontWeight:900}"
                        size="mini" :data="${className?uncap_first}List" style="width: 100%">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <#if dataList??>
                        <#list dataList as data>
                            <#if !data.autoIncrement >
                                <#if data.fieldType == 'Boolean'>
                    <el-table-column prop="${data.fieldName}" label="${data.columnComment}" :show-overflow-tooltip='true'>
                        <template slot-scope="scope">
                            <el-switch
                                    disabled
                                    v-model="scope.row.${data.fieldName}"
                                    active-color="#13ce66"
                                    inactive-color="#ff4949">
                            </el-switch>
                        </template>
                    </el-table-column>
                                    <#else>
                    <el-table-column prop="${data.fieldName}" label="${data.columnComment}" :show-overflow-tooltip='true'></el-table-column>
                                </#if>
                            </#if>
                        </#list>
                    </#if>
                    <el-table-column
                            fixed="right"
                            label="操作"
                            width="200">
                        <template slot-scope="scope">
                            <el-button @click="openEditDialog(scope.row)"
                                       icon="el-icon-edit" type="text"
                                       size="small">编辑
                            </el-button>
                            <el-button @click="delete${className}(scope.row)"
                                       icon="el-icon-delete" type="text"
                                       size="small">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </template>

            <div class="block">
                <el-pagination
                        style="float: right"
                        background
                        @size-change="handlePageSizeChange"
                        @current-change="handlePageNumChange"
                        :current-page="pageRequest.pageNum"
                        :page-sizes="[10, 50, 100, 200]"
                        :page-size="pageRequest.pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="pageResult.total">
                </el-pagination>
            </div>
        </el-card>
        <div>
            <el-dialog
                    width="720px"
                    top="5vh"
                    :title="event.title"
                    :visible.sync="dialogFormVisible">
                <el-form :inline="true" :model="form" :rules="${className?uncap_first}Rules" ref="form"
                         style="padding: 0px 50px" size="small">
                    <#if dataList??>
                        <#list dataList as data>
                            <#if !data.autoIncrement>
                                <#if data.fieldType == 'Date' && !mapping(keySet,'value')?seq_contains(data.fieldName)>
                                    <el-form-item label="${data.columnComment}" :label-width="formLabelWidth" prop="${data.fieldName}">
                                         <el-date-picker
                                            v-model="form.${data.fieldName}"
                                            format="yyyy-MM-dd HH:mm:ss"
                                            value-format="yyyy-MM-dd HH:mm:ss"
                                            type="datetime"
                                            placeholder="选择日期时间">
                                         </el-date-picker>
                                    </el-form-item>
                                <#elseif data.fieldType == 'Time' && !mapping(keySet,'value')?seq_contains(data.fieldName)>
                                    <el-form-item label="${data.columnComment}" :label-width="formLabelWidth" prop="${data.fieldName}">
                                         <el-time-picker
                                            v-model="form.${data.fieldName}"
                                            value-format="HH:mm:ss"
                                            :picker-options="{
                                            selectableRange: '00:00:00 - 23:59:59'}"
                                            placeholder="任意时间点">
                                         </el-time-picker>
                                    </el-form-item>
                                <#elseif data.fieldType == 'Boolean'>
                                    <el-form-item label="${data.columnComment}" :label-width="formLabelWidth" prop="${data.fieldName}">
                                        <el-switch
                                            v-model="form.${data.fieldName}"
                                            active-color="#13ce66"
                                            inactive-color="#ff4949"
                                            active-text="是"
                                            inactive-text="否">
                                        </el-switch>
                                    </el-form-item>
                                <#else>
                                <#if mapping(keySet,'value')?seq_contains(data.fieldName)>
                                    <el-form-item v-if="event.eventType === 0" label="${data.columnComment}" :label-width="formLabelWidth" prop="${data.fieldName}">
                                        <el-input v-model="form.${data.fieldName}" autocomplete="off"></el-input>
                                    </el-form-item>
                                <#else>
                                    <el-form-item label="${data.columnComment}" :label-width="formLabelWidth" prop="${data.fieldName}">
                                        <el-input v-model="form.${data.fieldName}" autocomplete="off"></el-input>
                                    </el-form-item>
                                </#if>
                                </#if>
                            </#if>
                        </#list>
                    </#if>
                </el-form>

                <div slot="footer" class="dialog-footer">
                    <el-button size="medium"
                               @click="dialogCancel">取 消</el-button>
                    <el-button type="primary" size="medium"
                               @click="submitForm('form')">确 定
                    </el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
    import {add${className}, delete${className}, get${className}List, update${className}} from "../../api/${className}";
    import {mapActions} from "vuex";
    import MessageBoxUtil from "@/utils/MessageBoxUtil";
    import DeepCopyUtil from "@/utils/DeepCopyUtil";

    export default {
        name: '${className}Manage.vue',
        data() {
            var validateNumber = (rule, value, callback) => {
                if (value && !/^-?\d*(\.\d+)?$/.test(value)) {
                    return callback(new Error('输入不合法，请输入数值'));
                } else {
                    callback();
                }
            };
            return {
                ${className?uncap_first}List: [],
                pageRequest: {
                    pageNum: 1,
                    pageSize: 10,
                    key: ''
                },
                pageResult: {
                    total: 0,
                    totalPage: 0,
                    size: 0,
                },
                dialogFormVisible: false,
                formLabelWidth: '90px',
                multipleSelection: [],
                event: {
                    eventType: 0,
                    title: ''
                },
                form: {},
                ${className?uncap_first}Rules: {
                    <#if dataList??>
                    <#list dataList as data>
                    <#if data.required || data.fieldType == 'Date' || numbers?seq_contains(data.fieldType) >
                    ${data.fieldName}: [
                        <#if data.required>
                        {required: true, message: '${data.columnComment}不能为空', trigger: 'blur'},
                        </#if>
                        <#if numbers?seq_contains(data.fieldType)>
                        {validator: validateNumber, trigger: 'blur'},
                        </#if>
                    ],
                    </#if>
                    </#list>
                    </#if>
                },
            }
        },
        //监听属性 类似于data概念
        computed: {
            deleteable(){
                return this.multipleSelection.length === 0
            }
        },
        //监控data中的数据变化
        watch: {},
        //方法集合
        methods: {
            ...mapActions('menu', ['refreshMenu']),

            openEditDialog(row) {
                this.dialogFormVisible = true;
                this.form = DeepCopyUtil.copy(row);
                this.event.eventType = 1
                this.event.title = "编辑${description}"
            },
            openNewDialog() {
                this.dialogFormVisible = true;
                this.form = {};
                this.event.eventType = 0
                this.event.title = "新增${description}"
            },
            get${className}List() {
                get${className}List(this.pageRequest).then(res => {
                    if (res.code === 200) {
                        this.${className?uncap_first}List = res.data.dataList
                        this.pageResult.size = res.data.size
                        this.pageResult.total = res.data.total
                        this.pageResult.totalPage = res.data.totalPage
                        if (res.data.size === 0 && res.data.pageNum > 1) {
                            this.pageRequest.pageNum--;
                            this.get${className}List();
                        }
                    }
                }).catch(err => {
                    this.$message({
                        type: 'error',
                        message: '数据加载失败，' + err.message
                    });
                })
            },
            delete${className}(row) {
                if (row){
                    this.multipleSelection = [row]
                }
                MessageBoxUtil.confirm("此操作将永久删除该数据，是否继续?", 'warn', () => {
                    delete${className}(this.multipleSelection).then(res => {
                        if (res.code === 200) {
                            this.get${className}List();
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                        } else {
                            this.$message({
                                type: 'error',
                                message: res.message,
                            });
                        }
                    }).catch(err => {
                        this.$message({
                            type: 'error',
                            message: "数据删除失败，" + err.message
                        });
                    })
                })
            },
            submitForm(form) {
                this.$refs[form].validate((valid) => {
                    if (valid) {
                        this.event.eventType === 0 ? this.add${className}() : this.update${className}();
                    } else {
                        return false;
                    }
                });
            },
            add${className}() {
                add${className}(this.form).then(res => {
                    if (res.code === 200) {
                        this.dialogFormVisible = false;
                        this.get${className}List()
                        this.$message({
                            message: '新增成功',
                            type: 'success'
                        });
                    } else {
                        this.$message({
                            type: 'error',
                            message: res.message
                        });
                    }
                }).catch(err => {
                    this.$message({
                        type: 'error',
                        message: '数据新增失败，' + err.message
                    });
                })
            },
            update${className}() {
                update${className}(this.form).then(res => {
                    if (res.code === 200) {
                        this.dialogFormVisible = false;
                        this.get${className}List()
                        this.$message({
                            message: '修改成功',
                            type: 'success'
                        });
                    } else {
                        this.$message({
                            type: 'error',
                            message: res.message
                        });
                    }
                }).catch(err => {
                    this.$message({
                        type: 'error',
                        message: '数据修改失败，' + err.message
                    });
                })
            },
            dialogCancel() {
                this.dialogFormVisible = false;
                this.get${className}List()
            },
            handlePageSizeChange(pageSize) {
                this.pageRequest.pageSize = pageSize;
                this.get${className}List()
            },
            handlePageNumChange(pageNum) {
                this.pageRequest.pageNum = pageNum;
                this.get${className}List()
            },
            handleSelectionChange(rows) {
                this.multipleSelection = rows;
            },
            goBack() {
                window.history.back()
            },
        },
        //生命周期 - 创建完成（可以访问当前this实例）
        created() {
            this.get${className}List()
        },
        //生命周期 - 挂载完成（可以访问DOM元素）
        mounted() {
        },
    };
</script>

<style scoped>

    .header {
        /*display: flex;*/
        /*!*垂直对齐*!*/
        /*align-items: center;*/
        height: 50px;
        background-color: #EAEEED;
    }

    .page-header {
        float: left;
        margin-top: 15px
    }

    .search {
        float: right;
        margin-top: 10px
    }

    .box-card {
        height: 100%;
    }

    .block {
        margin-top: 5px;
    }

    .el-input, .el-select {
        width: 185px
    }

    .el-form-item {
        width: 280px;
    }


</style>
